import React, { Component, Fragment } from 'react';

import { Upload, Modal, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

import { IMG_UPLOAD_URL, IMG_URL, reqDeleteIMG } from '../../../../api';

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    })
}

export default class ImgUpload extends Component {
    state = {
        previewVisible: false,
        previewImage: '',
        previewTitle: '',
        fileList: [],
    }

    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };

    handleChange = async ({ file, fileList }, setFieldsValue) => {

        if (file.status === 'removed') {
            const res = await reqDeleteIMG(file.name);
            if (res.status === 0) {
                message.success('图片删除成功！');
            } else {
                file.status = 'upload'
                message.error(res.msg);
            }
        } else if (file.status === 'done') {
            const res = file.response;
            if (res.status === 0) {
                const { data } = res;
                const file = fileList[fileList.length - 1];
                file.name = data.name;
                file.url = IMG_URL + data.url.substring(data.url.lastIndexOf('/') + 1);
                message.success('图片上传成功！');
            } else {
                message.error(res.msg);
            }
        }
        setFieldsValue({ imgs: fileList.map(item => item.name) });
        this.setState({ fileList });
    };

    componentDidMount() {
        const { product, setFieldsValue } = this.props;
        if (product && product.imgs) {
            const fileList = product.imgs.map((item, idx) => {
                return {
                    uid: item + '' + -idx,
                    name: item + '',
                    status: 'done',
                    url: IMG_URL + item,
                }
            });
            setFieldsValue({ imgs: fileList.map(item => item.name) });
            this.setState({ fileList });
        }
    }

    render() {
        const { previewVisible, previewImage, fileList, previewTitle } = this.state;
        const { setFieldsValue } = this.props;

        const uploadButton = (
            <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>上传文件</div>
            </div>
        );
        return (
            <Fragment>
                <Upload
                    accept="image/*"
                    action={IMG_UPLOAD_URL}
                    listType="picture-card"
                    name="image" // 请求参数名
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={arg => this.handleChange(arg, setFieldsValue)}
                >
                    {fileList.length >= 4 ? null : uploadButton}
                </Upload>
                <Modal
                    visible={previewVisible}
                    title={previewTitle}
                    footer={null}
                    onCancel={this.handleCancel}
                >
                    <img alt="product-img" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </Fragment>
        );
    }
}